package com.example.templatedemo

import android.Manifest
import android.R.attr.data
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.example.lib_common.base.BaseMvvmActivity
import com.example.lib_common.base.EdgePopDialog
import com.example.lib_common.logger.Logger
import com.example.lib_common.utils.switchFragment
import com.example.templatedemo.databinding.ActivityMainBinding
import com.google.gson.Gson
import org.json.JSONArray


class MainActivity : BaseMvvmActivity<ActivityMainBinding, MainVM>() {
    val items = List(50) { "这是第 $it 个条目" }
    private val mAdapter = SimpleAdapter()
    private var edgePopDialog: EdgePopDialog? = null

    override fun initView() {
        Logger.setEnable(true)
        val content: View = findViewById(android.R.id.content)
        content.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                // Check whether the initial data is ready.
                return if (true) {
                    // The content is ready. Start drawing.
                    content.viewTreeObserver.removeOnPreDrawListener(this)
                    true
                } else {
                    // The content isn't ready. Suspend.
                    false
                }
            }
        })
        super.initView()
//        splashScreen.set{
//            SystemClock.sleep(2000)
//            false
//        }
        mBinding.recyclerView.adapter = mAdapter
        mAdapter.submitList(items)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            startActivity(Intent(this, ScanActivity::class.java))
            Toast.makeText(this, adapter.items[position], Toast.LENGTH_SHORT).show()
        }
//        val navHostFragment =
//            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
//        val navController = navHostFragment.findNavController()

        mBinding.bottomNavigationView.setOnNavigationItemSelectedListener { item ->
            val fragmentTag = when (item.itemId) {
                R.id.nav_home -> "HomeFragment"
                R.id.nav_square -> "SquareFragment"
                R.id.nav_pub -> "PublicFragment"
                else -> "HomeFragment"
            }
            switchFragment(fragmentTag, R.id.nav_host_fragment, ::provideFragment)
            true
        }

        mBinding.bt.setOnClickListener {
//            Logger.setEnable(true)
//            mViewModel.getH5Url()
//            if (isPermissionDeniedForever(Manifest.permission.CAMERA)) {
//                Log.d("hjw_debug", "isPermissionDeniedForever")
//            } else {
//                requestPer(Manifest.permission.CAMERA) {
//
//                    Log.d("hjw_debug", "result:$it")
//                }
//            }

            Logger.json(items.joinToString(prefix = "[", postfix = "]") { "\"$it\"" })
            mViewModel.getH5Url()

//            // 顶部弹出（常用于顶部筛选面板）
//            edgePopDialog = EdgePopDialog.newInstance(
//                R.layout.dialog_edge_content, EdgePopDialog.Anim.BOTTOM
//            ) { contentView ->
//                contentView.findViewById<TextView>(R.id.tv)?.setOnClickListener {
//                    Logger.d("setOnClickListener")
//                }
//                contentView.findViewById<EditText>(R.id.edit)?.filters =
//                    arrayOf<InputFilter>(InputFilter.LengthFilter(8))
//            }
//
//            edgePopDialog?.show(supportFragmentManager, "bottom")
        }


        mBinding.bt2.setOnClickListener {
            requestPers(
                listOf(
                    Manifest.permission.CAMERA, Manifest.permission.BLUETOOTH_SCAN
                )
            ) { result ->
                result.forEach { perm, granted ->
                    Log.d("hjw_debug", "result:$it")
                }
            }
        }
    }

    private fun provideFragment(tag: String): Fragment? {
        return when (tag) {
            "HomeFragment" -> HomeFragment()
            "SquareFragment" -> SquareFragment()
            "PublicFragment" -> PublicFragment()
            else -> null
        }
    }

//    private fun switchFragment(fragmentTag: String) {
//        val fm = supportFragmentManager
//        val transaction = fm.beginTransaction()
//        fm.fragments.forEach { transaction.hide(it) }
//
//        val fragment = fm.findFragmentByTag(fragmentTag) ?: when (fragmentTag) {
//            "HomeFragment" -> HomeFragment()
//            "SquareFragment" -> SquareFragment()
//            "PublicFragment" -> PublicFragment()
//            else -> HomeFragment()
//        }.also { transaction.add(R.id.nav_host_fragment, it, fragmentTag) }
//
//        transaction.show(fragment)
//        transaction.setPrimaryNavigationFragment(fragment)
//        transaction.commitAllowingStateLoss()
//    }

    override fun beforeOnCreate(savedInstanceState: Bundle?) {
        val splashScreen = installSplashScreen()
//        splashScreen.setKeepOnScreenCondition { true }
//        splashScreen.setOnExitAnimationListener { splashScreenView ->
//            // Create your custom animation.
//            val slideUp = ObjectAnimator.ofFloat(
//                splashScreenView.view,
//                View.TRANSLATION_Y,
//                0f,
//                -splashScreenView.view.height.toFloat()
//            )
//            slideUp.interpolator = AnticipateInterpolator()
//            slideUp.duration = 200L
//
//            // Call SplashScreenView.remove at the end of your custom animation.
//            slideUp.doOnEnd { splashScreenView.remove() }
//
//            // Run your animation.
//            slideUp.start()
//        }
    }

    override fun getInsetTypeMask(): Int {
        return WindowInsetsCompat.Type.statusBars()
    }

    override fun softKeyboardCallBack(keyboardHeight: Int) {
        super.softKeyboardCallBack(keyboardHeight)
        Log.d("hjw_debug", "keyboardHeight:$keyboardHeight")
        if (keyboardHeight > 300) {
//            mBinding.recyclerView.scrollToPosition(mAdapter.itemCount - 1)
        }
        edgePopDialog?.dialog?.window?.decorView?.setPadding(0, 0, 0, keyboardHeight)
    }
}